package com.njym.test;

import org.junit.Test;
import sun.misc.BASE64Encoder;

import java.security.*;

/**
 * 加密
 *
 * @author zhy
 * @date 2019-03-06 10:45
 **/
public class RSA {
	public static final String KEY_SHA = "SHA";

//	@Test
//	public void addPwd() {
//		String inputStr = "123456";
//		BigInteger sha;
//		System.out.println("=======加密前的数据:" + inputStr);
//		byte[] inputData = inputStr.getBytes();
//		try {
//			MessageDigest messageDigest = MessageDigest.getInstance(KEY_SHA);
//			messageDigest.update(inputData);
//			sha = new BigInteger(messageDigest.digest());
//			System.out.println("SHA加密后:" + sha.toString(32));
//		}
//		catch (Exception e) {
//			e.printStackTrace();
//		}
//	}

	/*
	 * 产生RSA公私钥对
	 */
	@Test
	public void genRSAKeyPair() {
		KeyPairGenerator rsaKeyGen = null;
		KeyPair rsaKeyPair = null;
		try {
			System.out.println("Generating a pair of RSA key ... ");
			rsaKeyGen = KeyPairGenerator.getInstance("RSA");
			SecureRandom random = new SecureRandom();
			random.nextBytes(new byte[1]);
			rsaKeyGen.initialize(1024, new SecureRandom());
			rsaKeyPair = rsaKeyGen.genKeyPair();
			PublicKey rsaPublic = rsaKeyPair.getPublic();
			PrivateKey rsaPrivate = rsaKeyPair.getPrivate();
			System.out.println("1024-bit RSA key GENERATED.");
		} catch (Exception e) {
			System.out.println("Exception in keypair generation. Reason: " + e);
		}
		String encode = new BASE64Encoder().encode(rsaKeyPair.getPublic().getEncoded());
		String encode1 = new BASE64Encoder().encode(rsaKeyPair.getPrivate().getEncoded());

		System.out.println("pub:"+ encode);
		System.out.println("pri:"+encode1);
//		return rsaKeyPair;
	}

}
